package cn.zifangsky.license;

import cn.zifangsky.config.LicenseVerifyProperties;
import cn.zifangsky.model.LicenseVerifyParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 在项目启动时安装证书
 *
 * @author wb
 * @date 2023/4/24
 * @since 1.0.0
 */
@Component
@ConditionalOnProperty(prefix = "license.verify", name = "enabled", havingValue = "true")
@PropertySource({"license-config.properties"}) //加载额外的配置
@EnableConfigurationProperties(LicenseVerifyProperties.class)
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {
    private static Logger logger = LogManager.getLogger(LicenseCheckListener.class);

    @Resource
    LicenseVerifyProperties verifyProperties;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //root application context 没有parent
        ApplicationContext context = event.getApplicationContext().getParent();
        if (context == null) {
            if (StringUtils.isNotBlank(verifyProperties.getLicensePath())) {
                logger.info("++++++++ 开始安装证书 ++++++++");

                LicenseVerifyParam param = new LicenseVerifyParam();
                param.setSubject(verifyProperties.getSubject());
                param.setPublicAlias(verifyProperties.getPublicAlias());
                param.setStorePass(verifyProperties.getStorePass());
                param.setLicensePath(verifyProperties.getLicensePath());
                param.setPublicKeysStorePath(verifyProperties.getPublicKeysStorePath());

                LicenseVerify licenseVerify = new LicenseVerify();
                //安装证书
                licenseVerify.install(param);

                logger.info("++++++++ 证书安装结束 ++++++++");
            }
        }
    }
}
